<?php
//MyCurator_update.php
//
//This program hooks into the wordpress automatic updater and checks 
//for new updates.  It also displays info on the new update and
//allows you to automatically update to the new version
//
//API Endpoint
define('MCT_AI_UPDATEAPI','http://www.target-info.com/update-api/');
//Hook into the plugin update check
add_filter('pre_set_site_transient_update_plugins','mct_ai_updatecheck');
//Hook into the plugin details screen
add_filter('plugins_api', 'mct_ai_updateinfo',10,3);

function mct_ai_updatecheck($transient) {
    //Check for a newer version at our API
    // Check if the transient contains the 'checked info
    // Just return its value if no
    if (empty($transient->checked)) return $transient;
    
    //The transient contains the 'checked' info, 
    //append our API
    $plugin_slug = plugin_basename(plugin_dir_path(__FILE__).'MyCurator.php');
    
    //POST data for API
    $args = array(
        'action' => 'update-check',
        'plugin_name' => $plugin_slug,
        'version' => $transient->checked[$plugin_slug]
    );
    
    $response = mct_ai_updaterequest($args);
    
    //if false, don't make any changes
    if ($response !== false) $transient->response[$plugin_slug] = $response;
    
    return $transient;
}

function mct_ai_updateinfo($false, $action, $args) {
    //Check for information on the version at our API
    $plugin_slug = plugin_basename(plugin_dir_path(__FILE__).'MyCurator.php');
    
    //check if this plugin call is about us
    if ($args->slug != $plugin_slug) return false;
    
    //Post data to the API
    $postargs = array(
        'action' => 'plugin-information',
        'plugin_name' => $plugin_slug
    );
    
    return mct_ai_updaterequest($postargs);
}

function mct_ai_updaterequest($args) {
    //Send the request to our API
    //Should get back an object, or false
    
    $request = wp_remote_post(MCT_AI_UPDATEAPI, array('body' => $args));
    
    //check for success
    if (is_wp_error($request) || wp_remote_retrieve_response_code($request) != 200) {
        return false;  //request failed
    }    
    //unserialize and check if an object, return if so else return false
    $response = unserialize( wp_remote_retrieve_body($request));

    if (is_object($response)) {
        return $response;
    } else {
        return false;
    }
}

?>